from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification
from apps.meiduo_admin.serializers.sku import SKUModelSerializer, GoodsCategoryModelSerializer, \
    SPUListSerializer, GoodsSpecSerialzier
from apps.meiduo_admin.utils import PageNum


class SKUModelViewSet(ModelViewSet):
    # 指定查询集
    # queryset = Users.objects.all()

    # 指定序列化器
    serializer_class = SKUModelSerializer

    # 指定分页
    pagination_class = PageNum

    # 不指定指定查询集时调用的方法
    # 重写查询方法 简单实现过滤
    def get_queryset(self):
        keyword = self.request.query_params.get("keyword")

        if keyword:
            return SKU.objects.filter(username__contains=keyword)
        return SKU.objects.all()


class GoodsCategoryListAPIView(ListAPIView):
    # 指定查询集，只要三级分类
    queryset = GoodsCategory.objects.filter(subs=None)

    # 指定序列化器
    serializer_class = GoodsCategoryModelSerializer


class SPUListView(ListAPIView):
    # 指定查询集
    queryset = SPU.objects.all()

    # 指定序列化器
    serializer_class = SPUListSerializer

    # 指定分页
    # pagination_class = PageNum


# 获取所有spu规格 请求 /goods/2/specs/
class SPUSpecifcationAPIView(APIView):

    def get(self, request, spu_id):
        # 查询所有spu_id 为传过来的id
        specs = SPUSpecification.objects.filter(spu_id=spu_id)

        specsSerializer = GoodsSpecSerialzier(specs, many=True)

        return Response(specsSerializer.data)
